#!/bin/bash
#
# \brief   Boot ISO image in QEMU/KVM
# \author  Christian Helmuth
# \date    2009-02-05
#

if [ "$#" -lt "1" ]; then
	echo "usage: boot_iso [-tap] <image.iso>"
	exit 1
fi

#
# Parse command-line options
#
if [ "$1" == "-tap" ]; then
	CONFIG_TAP=true
	shift
fi

#
# File name of the ISO image taken from the command line
#
ISOIMG=$1

#
# Configure TUN/TAP
#
if [ -n "$CONFIG_TAP" ]; then
	TAPDEV=

	failed() {
		echo "TAP device setup failed. You must be permitted to sudo and have installed the tunctl utility."
		echo "Under Debian/Ubuntu execute: sudo apt-get install uml-utilities"
		exit 1
	}

	# Check for tunctl
	[ -n "$(type -t tunctl)" ] || failed

	# Create persistent tap0 owned by user $USER
	TAPDEV=$(sudo tunctl -b -u $USER) || failed

	# Setup device
	sudo /sbin/ifconfig $TAPDEV 10.9.02.1 || failed
fi

#
# Configuration, i.e. argument vector of QEMU command line
#
declare -a ARGV

#
# Configure the emulator program via the ARGV[0], e.g.,
#
#   ARGV[0]="qemu"         or
#   ARGV[0]="kvm"          or even
#   ARGV[0]="reset; qemu"
#
ARGV[0]="qemu"

#
# Standard arguments are in ARGV[1]. These can be extended by ARGV[>1] or
# overwritten in ARGV[1].
#
ARGV[1]="-m 64 -serial stdio -no-kqemu -cdrom $ISOIMG -boot d"

#
# Include local configuration, which may extend or override
# standard settings.
#
[ -r $PWD/boot_iso.cfg ] && . $PWD/boot_iso.cfg

#
# Execute configured QEMU commandline
#
eval ${ARGV[@]}

#
# Cleanup TUN/TAP
#
if [ -n "$CONFIG_TAP" ]; then

	# Remove tap device
	sudo tunctl -d $TAPDEV
fi
